/*
 * Copyright 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * Adapted for use with ABAP To Phone by John Patterson
 */
package com.jasper.android.atp;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.provider.Settings.Secure;
import android.util.Log;

public class DeviceRegistrar {
	private static final String TAG = "DeviceRegistrar";
	
	public static final String REGISTRATION_ID = "registration_id";
	public static final String ACCOUNT_NAME = "account_name";
	public static final String UPDATE_ACTION = "com.jasper.atp.UPDATE_UI";
	
    public static final String STATUS_EXTRA = "Status";
    public static final int REGISTERED_STATUS = 1;
    public static final int BAD_REQUEST_STATUS = 2;
    public static final int ERROR_STATUS = 3;
    public static final int UNREGISTERED_STATUS = 4;
	
	   public static void registerWithServer(final Context context, final String registrationID) {
		new Thread(new Runnable() {
			//Update in non blocking thread
			public void run() {
				// prepare to call back the registration activity
				Intent updateIntent = new Intent(UPDATE_ACTION);	
				try {
					HttpResponse res = makeRequest(context, registrationID);
					if (res.getStatusLine().getStatusCode() == 200) {
						SharedPreferences prefs = Prefs.get(context);
						SharedPreferences.Editor edit = prefs.edit();
						edit.putString(REGISTRATION_ID, registrationID);
						edit.commit();
						updateIntent.putExtra(STATUS_EXTRA, REGISTERED_STATUS);
					} else if (res.getStatusLine().getStatusCode() == 400) {		
						Log.w(TAG,"Registration error " + res.getStatusLine().getReasonPhrase());
						updateIntent.putExtra(STATUS_EXTRA, BAD_REQUEST_STATUS);
					} else {
						Log.w(TAG,"Registration error "
								+ String.valueOf(res.getStatusLine().getStatusCode())
								+ " " +	res.getStatusLine().getReasonPhrase() );
						updateIntent.putExtra(STATUS_EXTRA, ERROR_STATUS);
					}
					context.sendBroadcast(updateIntent);
				} catch (Exception e) {
					Log.w(TAG, "Registration error " + e.getMessage());
					updateIntent.putExtra(STATUS_EXTRA, ERROR_STATUS);
					context.sendBroadcast(updateIntent);
				}
			}
		}).start();
	}

	 public static void unregisterWithServer(Context context){
			// TODO unregister with server
			SharedPreferences prefs = Prefs.get(context);
			SharedPreferences.Editor edit = prefs.edit();
			edit.putString(DeviceRegistrar.REGISTRATION_ID, null);
			edit.commit();
			Log.i(TAG, "unRegistered");
			
			Intent updateIntent = new Intent(UPDATE_ACTION);
			updateIntent.putExtra(STATUS_EXTRA, UNREGISTERED_STATUS);
			context.sendBroadcast(updateIntent);
	 }
	   
	private static HttpResponse makeRequest(Context context, String regID)
			throws Exception {
		Log.d(TAG, "Posting registration ID to ABAP server");
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(URI.create(Prefs.SERVER_REGISTER_URL));
		SharedPreferences p = Prefs.get(context);

		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
		nameValuePairs.add(new BasicNameValuePair("email", p.getString(ACCOUNT_NAME, null)));

		String deviceId = Secure.getString(context.getContentResolver(),Secure.ANDROID_ID);
		nameValuePairs.add(new BasicNameValuePair("deviceId", deviceId));
		nameValuePairs.add(new BasicNameValuePair("registrationId", regID));
		post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		return (HttpResponse) client.execute(post);
	}

}
